package com.gainscha.sdk.demo.ui;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.gainscha.sdk.demo.R;
import com.gainscha.sdk.demo.util.Util;
import com.gainscha.sdk.demo.databinding.ActivityBitmapCanvasBinding;
import com.gainscha.sdk2.BitmapCanvas;
import com.gainscha.sdk2.Printer;
import com.gainscha.sdk2.command.Tspl;

import java.io.IOException;

/**
 * 打印图片绘制示例
 *
 * @author mxlei
 * @date 2021/7/20
 */
public class BitmapCanvasActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {

    private ActivityBitmapCanvasBinding binding;
    private Typeface typeface = null;
    private Bitmap generateBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBitmapCanvasBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.seekBarLetterSpace.setOnSeekBarChangeListener(this);
        binding.seekBarLineSpace.setOnSeekBarChangeListener(this);

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        try {
//            typeface = Typeface.createFromAsset(getAssets(), "SourceHanSansCN-Light_0.otf");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成打印内容（图片）
        binding.btnGenerateBitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                generateBitmap = generatePrintBitmap1();
                binding.image.setImageBitmap(generateBitmap);
            }
        });
        //执行打印
        binding.btnPrint.setOnClickListener(v -> {
            if (Printer.getConnectedPrinters().isEmpty()) {
                Toast.makeText(this, R.string.toast_printer_not_connect, Toast.LENGTH_SHORT).show();
                return;
            }
            if (generateBitmap == null) {
                Toast.makeText(this, R.string.toast_not_generate_picture, Toast.LENGTH_SHORT).show();
                return;
            }
            Printer printer = Printer.getConnectedPrinters().get(0);
            Tspl cmd = new Tspl();
            //标签大小（毫米，每毫米8个像素）
            cmd.addSize(generateBitmap.getWidth() / 8, generateBitmap.getHeight() / 8);
            //标签间隙
            cmd.addGap(0);
            //速度
            cmd.addSpeed(4);
            //浓度
            cmd.addDensity(6);
            //偏移
            cmd.addReference(0, 0);
            //方向
            cmd.addDirection(false, false);
            //切刀
            cmd.addCutter(false);
            //撕离
            cmd.addTear(true);
            //剥离
            cmd.addPeel(false);
            //清除缓冲区
            cmd.addCls();
            //添加图片
            cmd.addBitmap(0, 0, generateBitmap, generateBitmap.getWidth(), Tspl.BITMAP_MODE.OVERWRITE, false);
            //打印份数
            cmd.addPrint(1);
            //打印
            byte[] data = cmd.getBytes();
            try {
                printer.print(data, null);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(new String(data));
        });
    }

    /**
     * 显示Toast
     */
    private void showToast(final String content) {
        if (Thread.currentThread().getId() == Looper.getMainLooper().getThread().getId()) {
            Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BitmapCanvasActivity.this, content, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private int getLetterSpace(int fontSize) {
        float spacePx = fontSize * (binding.seekBarLetterSpace.getProgress() - 50) / 50f;
        return (int) spacePx;
    }


    private int getLineSpace(int fontSize) {
        float spacePx = fontSize * (binding.seekBarLineSpace.getProgress() - 50) / 50f;
        return (int) spacePx;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        binding.btnGenerateBitmap.performClick();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }


    /**
     * 生成用于打印的图片
     */
    private Bitmap generatePrintBitmap1() {
        int fontSize = 18;
        BitmapCanvas canvas = new BitmapCanvas(BitmapCanvasActivity.this, Bitmap.createBitmap(40 * 8, 60 * 8, Bitmap.Config.RGB_565));
        int y = 30;
        y = canvas.drawText(20, y, "COCA-COLA", fontSize = 18, typeface, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y = canvas.drawText(20, y, "ORIGINAL SOCIAL TEA", fontSize = 18, typeface, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 40;
        y = canvas.drawText(20, y, "A symbol of good", fontSize = 30, Typeface.DEFAULT, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 10;
        y = canvas.drawText(20, y, "Cool/Relaxing", fontSize = 20, Typeface.DEFAULT, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 45;
        y = canvas.drawText(20, y, "0006", fontSize = 60, Typeface.DEFAULT_BOLD, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 10;
        y = canvas.drawText(20, y, "Package 01/02", fontSize = 18, typeface, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 2;
        y = canvas.drawText(20, y, "2021-04-06 14:04", fontSize = 18, typeface, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 20;
        y = canvas.drawText(20, y, "With Coke, you will be the truth", fontSize = 18, typeface, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        y += 2;
        canvas.drawText(20, y, "020-1234-1234", fontSize = 18, typeface, Integer.MAX_VALUE, getLetterSpace(fontSize), getLineSpace(fontSize));
        try {
            canvas.drawImage(40 * 8 - 90, 10, Util.resizeBitmap(BitmapFactory.decodeStream(getAssets().open("canvas/ic_logo.jpeg")), 90, 90));
            canvas.drawImage(40 * 8 - 70, 60 * 8 - 70, Util.resizeBitmap(BitmapFactory.decodeStream(getAssets().open("canvas/ic_qrcode.png")), 60, 60));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return canvas.getDrawBitmap();
    }

    /**
     * 生成用于打印的图片
     */
    private Bitmap generatePrintBitmap2() {
        String orderNum = "201911190023";
        String carNum = "粤A00001";
        String payType = "预付/补缴";
        String parkLocation = "云南南路（延安东路-金陵中路）两侧";
        String parkDuration = "2020/11/1 16:03\n2020/11/1 18:35";
        String payPrice = "30元";

        //字体
        Typeface typefaceBold = Typeface.createFromAsset(getAssets(), "NotoSansCJK-Bold-6.otf");
        Typeface typefaceMedium = Typeface.createFromAsset(getAssets(), "NotoSansCJK-Medium-5.otf");
        Typeface typefaceRegular = Typeface.createFromAsset(getAssets(), "NotoSansCJK-Regular-1.otf");
        //字号
        int textSizeContent = 20;
        int textSizeTitle = 24;

        //绘制图片
        Bitmap bitmap = Bitmap.createBitmap(70 * 8, 1150, Bitmap.Config.RGB_565);
        BitmapCanvas canvas = new BitmapCanvas(this, bitmap);
        int x = 16 * 3;
        int y = 16 * 3;
        int padding = 16 * 3;
        canvas.drawText(x, y, "上海市机动车道路停车收费电子票据告知书", textSizeTitle, typefaceBold);
        y += textSizeContent + 10;
        canvas.drawLine(x, y, bitmap.getWidth() - padding, y, 2);
        y += textSizeContent + 10;
        canvas.drawText(x, y, "停车单号", textSizeContent, typefaceMedium);
        canvas.drawText((int) (x + 20 * 4.5), y, orderNum, textSizeContent, typefaceRegular);
        y += textSizeContent + 10;
        canvas.drawText(x, y, "车牌号码", textSizeContent, typefaceMedium);
        canvas.drawText((int) (x + 20 * 4.5), y, carNum, textSizeContent, typefaceRegular);
        y += textSizeContent + 10;
        canvas.drawText(x, y, "缴费类型", textSizeContent, typefaceMedium);
        canvas.drawText((int) (x + 20 * 4.5), y, payType, textSizeContent, typefaceRegular);
        y += textSizeContent + 10;
        canvas.drawText(x, y, "停车路段", textSizeContent, typefaceMedium);
        canvas.drawText((int) (x + 20 * 4.5), y, parkLocation, textSizeContent, typefaceRegular);
        y += textSizeContent + 10;
        canvas.drawText(x, y, "停放时段", textSizeContent, typefaceMedium);
        canvas.drawText((int) (x + 20 * 4.5), y, parkDuration, textSizeContent, typefaceRegular);
        y += textSizeContent + 30;
        canvas.drawText(x, y, "金    额", textSizeContent, typefaceMedium);
        canvas.drawText((int) (x + 20 * 4.5), y, payPrice, textSizeContent, typefaceRegular);
        y += textSizeContent + 20;
        canvas.drawText(x, y, "------------------- 电子票据开具方式 -------------------", textSizeContent + 2, typefaceMedium);
        y += textSizeContent + 20;
        canvas.drawText(x, y, "1、扫码下载“上海停车”官方APP、小程序", textSizeContent, typefaceRegular);
        y += textSizeContent + 10;

        try {
            Bitmap qrcode = BitmapFactory.decodeStream(getAssets().open("canvas/ic_qrcode.png"));
            qrcode = Util.resizeBitmap(qrcode, 200, 200);
            canvas.drawImage(x + x, y, qrcode);
            y += 230;
        } catch (IOException e) {
            e.printStackTrace();
        }
        canvas.drawText(x, y, "2、绑定您的手机号和车牌", textSizeContent, typefaceRegular);
        y += textSizeContent + 10;
        canvas.drawText(x, y, "3、下载电子票据", textSizeContent, typefaceRegular);
        y += textSizeContent + 20;
        canvas.drawText(x, y, "------------------------- 提示 -------------------------", textSizeContent + 2, typefaceMedium);
        y += textSizeContent + 20;
        canvas.drawText(x, y, carNum + " 的车主（单位） 您（单位）在 202 年 月 日之前，累计有 笔道路停车欠费记录，请您（单位）登录“上海停车“官方 APP、小程序（微信、支付宝）尽快补缴。", textSizeContent + 2, typefaceRegular, bitmap.getWidth() - padding - padding);
        y += 100;
        canvas.drawText(x, y, "------------------------ 注意事项 ------------------------", textSizeContent + 2, typefaceMedium);
        y += textSizeContent + 20;
        canvas.drawText(x, y, "1、 本告知书仅作为您（单位）本次停车付费的凭证，不作为电子票据。\n2、 如需要核实有关停车收费情况请致电  XXXXXXXXXXXXXX（各协管单位电话）。\n3、 如您需要电子票据的，请在即日起 30 天内，通过“上海停车”官方 APP、小程序（微信、支付宝）下载,如果您（单位）在下载电子票据过程中遇到问题，请将问题描述和您的姓名、电话等有效的联系方式反馈至邮箱 service@jtcx.sh.cn.", textSizeContent + 2, typefaceRegular, bitmap.getWidth() - padding - padding);
        y += 220;
        canvas.drawText(x, y, "---------------------------------------------------------", textSizeContent + 2, typefaceMedium);
        y += textSizeContent + 20;
        canvas.drawText(x + 60, y, "上海市交通委", textSizeContent + 2, typefaceRegular);
        return bitmap;
    }
}
